package org.jeecg.modules.wlhy.hyevent.listener;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.MessageTypeEnum;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.api.wlhy.app.utils.HttpUtils;
import org.jeecg.modules.api.wlhy.debang.bean.*;
import org.jeecg.modules.api.wlhy.debang.entity.DbOrder;
import org.jeecg.modules.api.wlhy.debang.service.IDbOrderService;
import org.jeecg.modules.third.digitalseal.utils.PdfToImageUtil;
import org.jeecg.modules.third.ecloud.sdk.EcloudSdkService;
import org.jeecg.modules.wlhy.company.entity.HyCompanyConfig;
import org.jeecg.modules.wlhy.company.service.IHyCompanyConfigService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyevent.constant.AhRealtimeEnum;
import org.jeecg.modules.wlhy.hyevent.constant.AlctEnum;
import org.jeecg.modules.wlhy.hyevent.dto.ShippingNoticeDTO;
import org.jeecg.modules.wlhy.hyevent.event.*;
import org.jeecg.modules.wlhy.hyevent.service.AhRealtimeReportService;
import org.jeecg.modules.wlhy.hyevent.service.LocationListenerService;
import org.jeecg.modules.wlhy.hyhistorytrace.entity.HyHistoryTrace;
import org.jeecg.modules.wlhy.hyhistorytrace.service.IHyHistoryTraceService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.hywarningmessage.entity.HyWarningMessage;
import org.jeecg.modules.wlhy.hywarningmessage.service.IHyWarningMessageService;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.report.ShippingNoteApiAlct56Service;
import org.jeecg.modules.wlhy.shipping.constant.ShippingStatus;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class HyEventListener  {

    @Autowired
    private ShippingNoteApiAlct56Service shippingNoteApiAlct56Service;

    @Autowired
    private LocationListenerService locationListenerService;

    @Autowired
    private IHyHistoryTraceService hyHistoryTraceService;

    @Autowired
    private IHyOrderService hyOrderService;

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Autowired
    private EcloudSdkService ecloudSdkService;

    @Autowired
    private IHyDriverService hyDriverService;

    @Autowired
    private IHyVehicleService hyVehicleService;

    @Autowired
    private IDbOrderService dbOrderService;

    @Autowired
    private IHyCompanyConfigService companyConfigService;

    @Autowired
    private AhRealtimeReportService ahRealtimeReportService;

    @Autowired
    private IHyWarningMessageService warningMessageService;

    @Async
    @Order
    @EventListener(AlctEvent.class)
    public void alctEventListener(AlctEvent alctEvent) throws InterruptedException {

        log.info("监听到辽宁税务事件, 参数：{}", JSONUtil.toJsonStr(alctEvent));
        if (StrUtil.isEmpty(alctEvent.getShippingId())) {
            return;
        }

        //action 2： 表示同步轨迹事件请求
        if (AlctEnum.ALCT_ACTION_SYNCTRACES == alctEvent.getAction()) {
            HyShippingNote hyShippingNote = new HyShippingNote();
            hyShippingNote.setId(alctEvent.getShippingId());
            Result result = this.shippingNoteApiAlct56Service.syncTraces(hyShippingNote);
            if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
                log.error("同步辽宁税务轨迹状态返回, {}", result);
            }
        }

        //action 4: 更新司机运费
        //if (AlctEnum.ALCT_ACTION_UPDATEPRICE == alctEvent.getAction()) {
        //    //更新运费事件延时1秒执行
        //    Thread.sleep(1000);
        //    HyShippingNote hyShippingNote = new HyShippingNote();
        //    hyShippingNote.setId(alctEvent.getShippingId());
        //    this.shippingNoteApiAlct56Service.updatePrice(hyShippingNote);
        //}

        return;
    }


    //德邦回传信息
    @Async
    @Order
    @EventListener(DeBangEvent.class)
    public void DeBangEventListener(DeBangEvent deBangEvent) {

        HyShippingNote shippingNote = deBangEvent.getShippingId();
        log.error("[开始事件-推送德邦-数据... ] jsonMessage:{}" ,JSONUtil.toJsonStr(shippingNote));
        String channel=deBangEvent.getUploadType();
        try {
            /*if(channel.equals("JJR")){
                HyOrder hyOrder =  JSONObject.parseObject(msg, HyOrder.class);
                DbOrder dbOrder = dbOrderService.getById(hyOrder.getOrderCode());
                DeBangAgent deBangAgent=new DeBangAgent();
                deBangAgent.setOrderCode(dbOrder.getOrderCode());
                deBangAgent.setAgentName("");
                deBangAgent.setAgentPhone("");
                deBangAgent.setCiphertxt("");
                deBangAgent.setUniqueId("");
                deBangAgent.setPlatformcode("");

                DeBangUrlRequest request=new DeBangUrlRequest();
                request.setRequestEntity(deBangAgent);
                request.setMsgId("OPEN_API_1000003");
                String res = HttpUtils.sendDeBang("http://openapi.deppon.com.cn:11169/tps-driver-api/rest/api/v1/open", JSON.toJSONString(request));
                DeBangRequest resBaseBean = JSONObject.parseObject(res, DeBangRequest.class);
                if(resBaseBean.getErrCode()!="1"){
                    hyOrder.setErrCodes(resBaseBean.getResponseEntity().getErrCodes());
                    hyOrderService.updateById(hyOrder);
                }
                LOGGER.debug("[开始消费REDIS消息队列-接收德邦-数据... ] jsonMessage:{}" ,resBaseBean);
            }*/
            if(channel.equals("CHE")){

                DbOrder dbOrder = dbOrderService.getById(shippingNote.getOrderCode());
                HyDriver hyDriver = hyDriverService.getById(shippingNote.getDriverId());
                HyVehicle hyVehicle = hyVehicleService.getById(shippingNote.getVehicleId());
                //精准整车
                if(dbOrder.getType().equals("order")){
                    DeBangVehicle deBangVehicle =new DeBangVehicle();
                    deBangVehicle.setPlatformcode(dbOrder.getPlatformcode());
                    deBangVehicle.setCiphertxt(dbOrder.getCiphertxt());
                    deBangVehicle.setOrderCode(dbOrder.getOrderCode());
                    deBangVehicle.setType("1");
                    deBangVehicle.setUniqueId(dbOrder.getUniqueId());
                    DeBangDriver deBangDriver =new DeBangDriver();
                    List<DeBangDriver> deBangDriverList =new ArrayList<>();
                    deBangDriver.setDriver_name(hyDriver.getDriverName());
                    deBangDriver.setPrice(dbOrder.getPrice());
                    deBangDriver.setDriver_phone(hyDriver.getTelephone());
                    deBangDriver.setVehicleno(hyVehicle.getVehicleNumber());
                    deBangDriver.setVehicleLength("4.2米");
                    deBangDriver.setModels("高栏");
                    deBangDriverList.add(deBangDriver);
                    deBangVehicle.setDriver_info(deBangDriverList);
                    DeBangUrlRequest request=new DeBangUrlRequest();
                    request.setRequestEntity(deBangVehicle);
                    request.setMsgId("OPEN_API_1000004");
                    log.error("[推送德邦-CHE 数据... ] jsonMessage:{}" ,JSON.toJSONString(request));
                    String res = HttpUtils.sendDeBang("http://openapi.deppon.com.cn:11169/tps-driver-api/rest/api/v1/open", JSON.toJSONString(request));
                    DeBangRequest resBaseBean = JSONObject.parseObject(res, DeBangRequest.class);
                    if(resBaseBean.getErrCode()!="1"){
                        shippingNote.setErrCodes(resBaseBean.getResponseEntity().getErrCodes());
                        hyShippingNoteService.updateById(shippingNote);
                    }
                    log.error("[接收德邦-CHE 数据... ] jsonMessage:{}" ,resBaseBean);
                }

            }
            if(channel.equals("CHE_DINGWEI")){
                DbOrder dbOrder = dbOrderService.getById(shippingNote.getOrderCode());
                HyVehicle hyVehicle = hyVehicleService.getById(shippingNote.getVehicleId());
                DeBangPositionInfo deBangPositionInfo =new DeBangPositionInfo();
//                deBangPositionInfo.setOrderCode(dbOrder.getOrderCode());
                deBangPositionInfo.setVehicleNo(hyVehicle.getVehicleNumber());
                deBangPositionInfo.setPlatformCode(dbOrder.getPlatformcode());
                deBangPositionInfo.setLatitude(shippingNote.getSendLatitude().toString());
                deBangPositionInfo.setLongitude(shippingNote.getSendLongitude().toString());
                deBangPositionInfo.setSpeed("20");
                deBangPositionInfo.setDirection("5.2");
                String dateFormat = DateUtils.getDate("yyyy-MM-dd HH:mm:ss");
                deBangPositionInfo.setLocateTime(dateFormat);

//                DeBangUrlRequest request=new DeBangUrlRequest();
//                request.setRequestEntity(deBangPositionInfo);
//                request.setMsgId("OPEN_API_1000001");
                List<DeBangPositionInfo> list =new ArrayList<>();
                list.add(deBangPositionInfo);
                log.error("[推送德邦-CHE_DINGWEI数据... ] jsonMessage:{}" ,JSON.toJSONString(list));
                String res = HttpUtils.sendDeBang2("http://openapi.deppon.com.cn:11169/iov-locus/carry/addTrack", JSON.toJSONString(list));
//                String res = HttpUtils.sendDeBang("http://openapi.deppon.com.cn:11169/tps-driver-api/rest/api/v1/open", JSON.toJSONString(request));
                DeBangRequest resBaseBean = JSONObject.parseObject(res, DeBangRequest.class);
                if(resBaseBean.getStatus().equals("200")){
//                    shippingNote.setShippingStatus("1");//测试
                    shippingNote.setErrCodes(resBaseBean.getStatus());
                    hyShippingNoteService.updateById(shippingNote);
                }else{
//                    shippingNote.setShippingStatus("1");//测试
                    shippingNote.setErrCodes(resBaseBean.getStatus());
                    hyShippingNoteService.updateById(shippingNote);
                }
                log.error("[接收德邦-CHE_DINGWEI数据... ] jsonMessage:{}" ,resBaseBean);
            }

            if(channel.equals("CHE_CHUFA")){

                DbOrder dbOrder = dbOrderService.getById(shippingNote.getOrderCode());
                HyDriver hyDriver = hyDriverService.getById(shippingNote.getDriverId());
                HyVehicle hyVehicle = hyVehicleService.getById(shippingNote.getVehicleId());
                if(dbOrder.getType().equals("order")){
                    dbOrder.setBiddingState("9");
                    DeBangUrlRequest request=new DeBangUrlRequest();
                    request.setRequestEntity(dbOrder);
                    request.setMsgId("OPEN_API_1000008");
                    log.error("[推送德邦-CHE_CHUFA数据... ] jsonMessage:{}" ,JSON.toJSONString(request));
                    String res = HttpUtils.sendDeBang("http://openapi.deppon.com.cn:11169/tps-driver-api/rest/api/v1/open", JSON.toJSONString(request));
                    DeBangRequest resBaseBean = JSONObject.parseObject(res, DeBangRequest.class);
                    if(resBaseBean.getErrCode()!="1"){
                        shippingNote.setShippingStatus("3");//设置状态为运输中
                        shippingNote.setStatusDtLoading(new Date());//实际装货完成时间
                        shippingNote.setErrCodes(resBaseBean.getDepartureArriveResponseEntity().getErrCodes());
                        hyShippingNoteService.updateById(shippingNote);
                    }
                    log.error("[接收德邦-CHE_CHUFA数据... ] jsonMessage:{}" ,resBaseBean);
                }else{
                    dbOrder.setBiddingState("9");
                    dbOrder.setStartTime(new Date().toString());
                    dbOrder.setVehicleNo(hyVehicle.getVehicleNumber());
                    dbOrder.setDriverName(hyDriver.getDriverName());
                    dbOrder.setDirverPhone(hyDriver.getTelephone());

                    DeBangUrlRequest request=new DeBangUrlRequest();
                    request.setRequestEntity(dbOrder);
                    request.setMsgId("OPEN_API_1000023");
                    log.error("[推送德邦-CHE_CHUFA数据... ] jsonMessage:{}" ,JSON.toJSONString(request));
                    String res = HttpUtils.sendDeBang("http://openapi.deppon.com.cn:11169/tps-driver-api/rest/api/v1/open", JSON.toJSONString(request));
                    DeBangRequest resBaseBean = JSONObject.parseObject(res, DeBangRequest.class);
                    if(resBaseBean.getErrCode()!="1"){
                        shippingNote.setShippingStatus("3");//设置状态为运输中
                        shippingNote.setStatusDtLoading(new Date());//实际装货完成时间
                        shippingNote.setErrCodes(resBaseBean.getDepartureArriveResponseEntity().getErrCodes());
                        hyShippingNoteService.updateById(shippingNote);
                    }
                    log.error("[接收德邦-CHE_CHUFA数据... ] jsonMessage:{}" ,resBaseBean);
                }

            }
            if(channel.equals("CHE_DAODA")){
                DbOrder dbOrder = dbOrderService.getById(shippingNote.getOrderCode());
                HyDriver hyDriver = hyDriverService.getById(shippingNote.getDriverId());
                HyVehicle hyVehicle = hyVehicleService.getById(shippingNote.getVehicleId());
                if(dbOrder.getType().equals("order")){
                    dbOrder.setBiddingState("10");
                    DeBangUrlRequest request=new DeBangUrlRequest();
                    request.setRequestEntity(dbOrder);
                    request.setMsgId("OPEN_API_1000008");
                    log.error("[推送德邦-CHE_DAODA 数据... ] jsonMessage:{}" ,JSON.toJSONString(request));
                    String res = HttpUtils.sendDeBang("http://openapi.deppon.com.cn:11169/tps-driver-api/rest/api/v1/open", JSON.toJSONString(request));
                    DeBangRequest resBaseBean = JSONObject.parseObject(res, DeBangRequest.class);
                    if(resBaseBean.getErrCode()!="1"){
                        shippingNote.setShippingStatus("5");//设置状态为已交货
                        shippingNote.setStatusDtSign(new Date());//货源完结时间
                        shippingNote.setErrCodes(resBaseBean.getDepartureArriveResponseEntity().getErrCodes());
                        hyShippingNoteService.updateById(shippingNote);
                    }
                    log.error("[接收德邦-CHE_DAODA 数据... ] jsonMessage:{}" ,resBaseBean);
                }else{
                    dbOrder.setBiddingState("10");
                    dbOrder.setStartTime(new Date().toString());
                    dbOrder.setVehicleNo(hyVehicle.getVehicleNumber());
                    dbOrder.setDriverName(hyDriver.getDriverName());
                    dbOrder.setDirverPhone(hyDriver.getTelephone());

                    DeBangUrlRequest request=new DeBangUrlRequest();
                    request.setRequestEntity(dbOrder);
                    request.setMsgId("OPEN_API_1000023");
                    log.error("[推送德邦-CHE_DAODA 数据... ] jsonMessage:{}" ,JSON.toJSONString(request));
                    String res = HttpUtils.sendDeBang("http://openapi.deppon.com.cn:11169/tps-driver-api/rest/api/v1/open", JSON.toJSONString(request));
                    DeBangRequest resBaseBean = JSONObject.parseObject(res, DeBangRequest.class);
                    if(resBaseBean.getErrCode()!="1"){
                        shippingNote.setShippingStatus("5");//设置状态为已交货
                        shippingNote.setStatusDtSign(new Date());//货源完结时间
                        shippingNote.setErrCodes(resBaseBean.getDepartureArriveResponseEntity().getErrCodes());
                        hyShippingNoteService.updateById(shippingNote);
                    }
                    log.error("[接收德邦-CHE_DAODA 数据... ] jsonMessage:{}" ,resBaseBean);
                }

            }
            if(channel.equals("DA_CHE")){
                DbOrder dbOrder = dbOrderService.getById(shippingNote.getOrderCode());
                HyDriver hyDriver = hyDriverService.getById(shippingNote.getDriverId());
                HyVehicle hyVehicle = hyVehicleService.getById(shippingNote.getVehicleId());

                if(!dbOrder.getType().equals("order")){
                    dbOrder.setVehicleNo(hyVehicle.getVehicleNumber());
                    dbOrder.setDimensional("100");
                    dbOrder.setWeight("100");
                    dbOrder.setDriverName(hyDriver.getDriverName());
                    dbOrder.setDirverPhone(hyDriver.getTelephone());
                    dbOrder.setQuantity("1");
                    dbOrder.setAbnormalMark("");
                    dbOrder.setJGoodsStartTime(new Date().getTime());
                    dbOrder.setJGoodsEndTime(new Date().getTime());
                    dbOrder.setDeliveryVehicleNumber(hyVehicle.getVehicleNumber());
                    DeBangUrlRequest request=new DeBangUrlRequest();
                    request.setRequestEntity(dbOrder);
                    request.setMsgId("OPEN_API_1000022");
                    log.error("[推送德邦-DA_CHE 数据... ] jsonMessage:{}" ,JSON.toJSONString(request));
                    String res = HttpUtils.sendDeBang("http://openapi.deppon.com.cn:11169/tps-driver-api/rest/api/v1/open", JSON.toJSONString(request));
                    DeBangRequest resBaseBean = JSONObject.parseObject(res, DeBangRequest.class);
                    if(resBaseBean.getErrCode()!="1"){
                        shippingNote.setErrCodes(resBaseBean.getResponseEntity().getErrCodes());
                        hyShippingNoteService.updateById(shippingNote);
                    }
                    log.error("[接收德邦-DA_CHE 数据... ] jsonMessage:{}" ,resBaseBean);
                }

            }



        } catch (Exception e) {
            log.error("[消费REDIS消息队列-德邦-数据失败，失败信息:{}]", e.getMessage());

        }

        return;
    }

    //司机SDK上报位置
    @Async
    @Order
    @EventListener(AppLocationEvent.class)
    public void appLocationListener(AppLocationEvent appLocationEvent) {

        if (null == appLocationEvent.getHyShippingNote()) {
            log.error("司机SDK上报参数错误， {}", appLocationEvent.getShippingId());
            return;
        }

        if (0 == appLocationEvent.getReportPlatformType()) {
            log.error("监管配置未开启， {}", appLocationEvent.getHyShippingNote().getShippingNoteNumber());
            return;
        }

        try {
            this.locationListenerService.uploadLocation(appLocationEvent);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上报部平台位置信息异常, {}", e.getMessage());
        }

        return;
    }


    //保存超过6个月的历史运单轨迹
    @Async
    @Order
    @EventListener(HistoryTraceEvent.class)
    public void historyTraceListener(HistoryTraceEvent historyTraceEvent) throws IOException {

        if (StrUtil.isEmpty(historyTraceEvent.getShippingNoteNumber()) || StrUtil.isEmpty(historyTraceEvent.getVehicleNumber())) {
            log.error("保存历史运单轨迹参数错误,{} {}", historyTraceEvent.getShippingNoteNumber(), historyTraceEvent.getVehicleNumber());
            return;
        }

        //如果历史轨迹已存在，并且当前运单已签收后就不再重复保存了
        HyHistoryTrace hyHistoryTrace = this.hyHistoryTraceService.getOne(new LambdaQueryWrapper<HyHistoryTrace>().eq(HyHistoryTrace::getShippingNoteNumber, historyTraceEvent.getShippingNoteNumber()));
        if (null != hyHistoryTrace) {
            if (0 < this.hyShippingNoteService.count(new LambdaQueryWrapper<HyShippingNote>()
                    .eq(HyShippingNote::getShippingNoteNumber, historyTraceEvent.getShippingNoteNumber())
                    .eq(HyShippingNote::getShippingStatus, ShippingStatus.已签收.getValue()))) {
                log.info("运单{} {}已有轨迹文件记录并且[已签收]，不再重复保存历史轨迹", historyTraceEvent.getShippingNoteNumber(), historyTraceEvent.getVehicleNumber());
                return;
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date currentDate = new Date();
        String currentDateStr = sdf.format(currentDate);

        String traceSavePath = this.uploadpath + File.separator + "traces" + File.separator + currentDateStr;
        log.info("打印保存历史轨迹参数,{} {} {}", historyTraceEvent.getShippingNoteNumber(), historyTraceEvent.getVehicleNumber(), traceSavePath);
        //如果没有traces目录，创建一个
        if (!FileUtil.exist(traceSavePath)) {
            FileUtil.mkdir(traceSavePath);
        }

        //写文件
        traceSavePath = traceSavePath + File.separator + historyTraceEvent.getShippingNoteNumber();
        PrintWriter pw = new PrintWriter(new FileWriter(traceSavePath));
        pw.print(JSONUtil.toJsonStr(historyTraceEvent));
        pw.flush();
        pw.close();

        //有则更新，无则保存
        if (null == hyHistoryTrace) {
            HyHistoryTrace saveTrace = HyHistoryTrace.builder()
                    .shippingNoteNumber(historyTraceEvent.getShippingNoteNumber())
                    .vehicleNumber(historyTraceEvent.getVehicleNumber())
                    .mileage(historyTraceEvent.getMileage())
                    .startTime(LocalDateTime.parse(historyTraceEvent.getStartTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                    .endTime(LocalDateTime.parse(historyTraceEvent.getEndTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                    .traceFilepath(traceSavePath)
                    .createTime(LocalDateTime.now())
                    .build();
            if (this.hyHistoryTraceService.save(saveTrace)) {
                log.info("历史轨迹保存成功,{} {} {}", historyTraceEvent.getShippingNoteNumber(), historyTraceEvent.getVehicleNumber(), traceSavePath);
            }
        } else {
            HyHistoryTrace saveTrace = HyHistoryTrace.builder()
                    .id(hyHistoryTrace.getId())
                    .shippingNoteNumber(historyTraceEvent.getShippingNoteNumber())
                    .vehicleNumber(historyTraceEvent.getVehicleNumber())
                    .mileage(historyTraceEvent.getMileage())
                    .startTime(LocalDateTime.parse(historyTraceEvent.getStartTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                    .endTime(LocalDateTime.parse(historyTraceEvent.getEndTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                    .traceFilepath(traceSavePath)
                    .createTime(LocalDateTime.now())
                    .build();
            if (this.hyHistoryTraceService.updateById(saveTrace)) {
                log.info("更新历史轨迹成功,{} {} {}", historyTraceEvent.getShippingNoteNumber(), historyTraceEvent.getVehicleNumber(), traceSavePath);
            }
        }


        return;
    }

    @Async
    @Order
    @EventListener(PicDownloadEvent.class)
    public void picDownloadListener(PicDownloadEvent picDownloadEvent) throws IOException {

        String type = picDownloadEvent.getType();
        String downloadUrl = picDownloadEvent.getDownloadUrl();
        if (StrUtil.isEmpty(downloadUrl)) {
            return;
        }

        //服务器文件夹
        String savefolderPath = picDownloadEvent.getServerFolderPath() + File.separator + picDownloadEvent.getServerFolderName();
        if (!FileUtil.exist(savefolderPath)) {
            FileUtil.mkdir(savefolderPath);
        }

        try {
            //取文件名xxx.jpg
            int lastIndex = downloadUrl.lastIndexOf('/');
            String filename = downloadUrl.substring(lastIndex);

            File file = new File(savefolderPath + filename);
            if (file.exists()) {
                log.warn("图片已存在, {} {}", picDownloadEvent.getServerFolderName(), downloadUrl);
                return;
            }

            long result = HttpUtil.downloadFile(downloadUrl, savefolderPath + filename);

            //如果文件名不是PDF需要改成PDF文件
            if (picDownloadEvent.getType().equals("contract") || picDownloadEvent.getType().equals("bill")) {
                //如果不是PDF需要转PDF
                if (!filename.contains(".pdf")) {
                    //文件名去除后缀
                    String filenameNoSubfix = filename.substring(0, filename.lastIndexOf("."));
                    String prefix = filename.substring(filename.indexOf(".") + 1);
                    log.info("开始转换PDF文件, {} , {} ,{}", type, filename, prefix);
                    PdfToImageUtil.imageToPdf(savefolderPath + filename, savefolderPath + filenameNoSubfix + ".pdf");
                }
            }

            log.info("下载图片结果 : {} -> {} -> {} -> {}", type, downloadUrl, savefolderPath + filename, result);
        } catch (Exception e) {
            log.error("下载图片异常 : {} ->  {} -> {} -> {}", type, e.getMessage(), picDownloadEvent.getServerFolderName(), downloadUrl);
        }

        return;
    }


    /**
     * 安徽运单1签收实时上报 ，运单2对账提交实时上报
     * @param reportEvent
     */
    @Async
    @Order
    @EventListener(AhRealtimeReportEvent.class)
    public void AhRealtimeReportEventListener(AhRealtimeReportEvent reportEvent) {

        HyShippingNote hyShippingNote = this.hyShippingNoteService.getById(reportEvent.getShippingId());

        HyCompanyConfig companyConfig = this.companyConfigService.getOne(new QueryWrapper<HyCompanyConfig>()
                .eq("company_id", hyShippingNote.getCompanyId()));
        if (companyConfig == null) {
            log.error("[安徽运单1忽略上报] 上报公司配置信息不存在, {}", hyShippingNote.getShippingNoteNumber());
            return;
        }

        if (reportEvent.getAhRealtimeType().getCode().equals(AhRealtimeEnum.AH_REALTIME_REPORT_STEP1.getCode())) {
            this.ahRealtimeReportService.reportDriver(hyShippingNote, companyConfig);
            this.ahRealtimeReportService.reportVehicle(hyShippingNote, companyConfig);
            this.ahRealtimeReportService.reportStep1(hyShippingNote, companyConfig);
        } else if (reportEvent.getAhRealtimeType().getCode().equals(AhRealtimeEnum.AH_REALTIME_REPORT_STEP2.getCode())) {
            this.ahRealtimeReportService.reportStep2(hyShippingNote, companyConfig);
        } else {
            log.error("[安徽运单忽略上报] 上报类型错误, {} {}", hyShippingNote.getShippingNoteNumber(), reportEvent.getAhRealtimeType().getCode());
        }

        return;
    }


    /**
     * 运单通知消息监听
     */
    @Async
    @Order
    @EventListener(ShippingNoticeEvent.class)
    public void ShippingNoticeEventListener(ShippingNoticeEvent shippingNoticeEvent) {

        log.info("运单通知消息监听, {}", shippingNoticeEvent.getShippingNoteNumber());

        HyDriver hyDriver = this.hyDriverService.getById(shippingNoticeEvent.getDriverId());
        HyVehicle hyVehicle = this.hyVehicleService.getById(shippingNoticeEvent.getVehicleId());
        if (null == hyDriver || null == hyVehicle || null == shippingNoticeEvent.getLoginUser()) {
            log.error("运单通知消息参数错误, {} , {} , {}", shippingNoticeEvent.getShippingNoteNumber(), shippingNoticeEvent.getDriverId(), shippingNoticeEvent.getVehicleId());
            return;
        }

        HyShippingNote hyShippingNote = this.hyShippingNoteService.getById(shippingNoticeEvent.getShippingId());
        //HyOrder hyOrder = this.hyOrderService.getById(hyShippingNote.getOrderId());

        //组装消息数据
        ShippingNoticeDTO shippingNoticeDTO = ShippingNoticeDTO.builder()
                .shippingNoteNumber(hyShippingNote.getShippingNoteNumber())
                .driverName(hyDriver.getDriverName())
                .vehicleNumber(hyVehicle.getVehicleNumber())
                .updateBy(shippingNoticeEvent.getLoginUser().getRealname())
                .time(DateUtils.dateTimeToString(shippingNoticeEvent.getDateTime()))
                .build();

        String msgContent = StrUtil.EMPTY;
        Integer msgType = shippingNoticeEvent.getMsgType();
        //TODO 这里的判断将来可以根据不同的运输节点提示不同的消息内容，现阶段都是一样的
        if (msgType.equals(MessageTypeEnum.MESSAGE_TYPE_LOAD.getCode())) {
            msgContent = String.format("运输路线[%s -> %s]",
                    hyShippingNote.getSendAddressName(),
                    hyShippingNote.getReceiveAddressName());
            shippingNoticeDTO.setType("已装货");
        } else if (msgType.equals(MessageTypeEnum.MESSAGE_TYPE_UNLOAD.getCode())) {
            msgContent = String.format("运输路线[%s -> %s]",
                    hyShippingNote.getSendAddressName(),
                    hyShippingNote.getReceiveAddressName());
            shippingNoticeDTO.setType("已卸货");
        } else if (msgType.equals(MessageTypeEnum.MESSAGE_TYPE_SIGN.getCode())) {
            msgContent = String.format("运输路线[%s -> %s]",
                    hyShippingNote.getSendAddressName(),
                    hyShippingNote.getReceiveAddressName());
            shippingNoticeDTO.setType("已签收");
        } else if (msgType.equals(MessageTypeEnum.MESSAGE_TYPE_CHECK.getCode())) {
            msgContent = String.format("运输路线[%s -> %s]",
                    hyShippingNote.getSendAddressName(),
                    hyShippingNote.getReceiveAddressName());
            shippingNoticeDTO.setType("对账完成");
        }
        shippingNoticeDTO.setText(msgContent);

        HyWarningMessage warningMessage = warningMessageService.getOne(new LambdaQueryWrapper<HyWarningMessage>()
                .eq(HyWarningMessage::getObjectId, shippingNoticeEvent.getShippingId())
                .eq(HyWarningMessage::getCreateBy, "systemNotice")
        );

        if (null == warningMessage) {
            warningMessage = HyWarningMessage.builder()
                    .objectId(shippingNoticeEvent.getShippingId())
                    .messageType(shippingNoticeEvent.getMsgType())
                    .messageStatus(1)
                    .messageContent(JSONUtil.toJsonStr(shippingNoticeDTO))
                    .userId(hyDriver.getId())
                    .createBy("systemNotice")
                    .createTime(new Date())
                    .build();
        } else {
            warningMessage.setMessageContent(JSONUtil.toJsonStr(shippingNoticeDTO));
            warningMessage.setMessageType(shippingNoticeEvent.getMsgType());
            warningMessage.setCreateTime(new Date());
        }

        //保存消息通知
        warningMessageService.saveOrUpdate(warningMessage);
        return;
    }


}
